package com.supermap.utils;

import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * @Author zhangming
 * @Description TODO
 * @Date 2020/3/24 8:49
 * @Vsrsion 1.0.0
 **/
public class HttpClientUtil {

	/**
	 * post请求
	 * 
	 * @param url
	 * @param jsonstr
	 * @param charset
	 * @return
	 */
	@SuppressWarnings("resource")
	public static String RunPost(String url, String jsonstr, JSONObject header, String charset) {
			HttpClient httpClient = null;
			HttpPost httpPost = null;
			String result = null;
			try{
				httpClient = new SSLClient();
				httpPost = new HttpPost(url);
				if (header != null) {
					for (Map.Entry<String, Object> entry : header.entrySet()) {
						httpPost.addHeader(entry.getKey(), entry.getValue().toString());
					}
				}
				httpPost.addHeader("Content-Type", "application/json");
//				httpPost.addHeader("Accept","*/*");
				StringEntity se = new StringEntity(jsonstr);
				se.setContentType("text/json");
				se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
				httpPost.setEntity(se);
				HttpResponse response = httpClient.execute(httpPost);
				if(response != null){
					HttpEntity resEntity = response.getEntity();
					if(resEntity != null){
						result = EntityUtils.toString(resEntity,charset);
					}
				}
			}catch(Exception ex){
				ex.printStackTrace();
			}
			return result;
	}

	/**
	 * @Author zhangming
	 * @Description TODO
	 * @Date 2020/3/24 8:47
	 * @Param [url, charset]
	 * @return java.lang.String
	 **/
	public static String doGet(String url, String charset) {
		if (null == charset) {
			charset = "utf-8";
		}
		HttpClient httpClient = null;
		HttpGet httpGet = null;
		String result = null;

		try {
			httpClient = new SSLClient();
			httpGet = new HttpGet(url);

			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
}
